<?php

// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2019 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://demo.thinkadmin.top
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | gitee 代码仓库：https://gitee.com/zoujingli/ThinkAdmin
// | github 代码仓库：https://github.com/zoujingli/ThinkAdmin
// +----------------------------------------------------------------------

namespace app\store\controller;

use app\company\service\DataService;
use library\Controller;
use think\Db;
use think\facade\Config;
use app\wechat\controller\WechatTool;
/**
 * 会员管理
 * Class User
 * @package app\worker\controller
 */
class Viplist extends Controller
{

    /**
     * 绑定当前数据表
     * @var string
     */
    // protected $table = 'CompanyUser';
    
	protected $table1 = 'CompanyUserDepartment';
	protected $table_department = 'SystemMenu';
	protected $view_table = 'view_commodity_orders';
	protected $table = 'commodity_orders';
	protected $user = 'user';
    /**
     * 会员列表-默认个人会员
     * @auth true
     * @menu true
     * @throws \think\Exception
	 
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function index()
    {
        $this->title = 'VIP名单管理';	
		$dbconf = $this->getconfig('vister_db');
		$create_at_first=trim($this->request->param('create_at_first'));
		$create_at_last=trim($this->request->param('create_at_last'));
		$member_type = $this->request->param('member_type');

		if(!$create_at_first && !$create_at_last){
			//var_dump(time());

		switch ($this->request->param('status')) {
			case '1':
				$where = 'vip_date > '.time();
				# code...
				break;
			case '2':
				$where = 'vip_date < '.time();
				# code...
				break;
			default:
				$where = '';
				# code...
				break;
		}
        if($member_type){
            $this->assign('member_type',1);
            if($where){
                $where = $where.'';
            }else{
                $where = '';
            }
        }

		$this->_query(Db::connect($dbconf)->table('view_user_store_member'))
										  ->where($where)
										  ->like('username,company_name')
				  							  // ->equal('status')
				  						   ->page();
			}
			else{
				$query = $this->_query(Db::connect($dbconf)->table('view_user_store_member'))
														   ->where($where)
														   ->like('username,company_name')
														   ->where('create_at','<= time',$create_at_last)
														   ->where('create_at','> time',$create_at_first)
														   ->page();								
			}

    }

    /**
     * 会员列表-企业
     * @auth true
     * @menu true
     * @throws \think\Exception
     
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function indexcompany()
    {
        $this->title = '企业会员列表';   
        $dbconf = $this->getconfig('vister_db');
        $create_at_first=trim($this->request->param('create_at_first'));
        $create_at_last=trim($this->request->param('create_at_last'));
        $member_type = $this->request->param('member_type');
        if(!$create_at_first && !$create_at_last){
            //var_dump(time());

        switch ($this->request->param('status')) {
            case '1':
                $where = 'vip_date > '.time();
                # code...
                break;
            case '2':
                $where = 'vip_date < '.time();
                # code...
                break;
            default:
                $where = '';
                # code...
                break;
        }
        if($member_type){
            $this->assign('member_type',2);
            if($where){
                $where = $where.'';
            }else{
                $where = '';
            }
        }

        $this->_query(Db::connect($dbconf)->table('view_company_store_member'))
                                          ->where($where)
                                          ->like('username,company_name')
                                              // ->equal('status')
                                           ->page();
            }
            else{
                $query = $this->_query(Db::connect($dbconf)->table('view_company_store_member'))
                                                           ->where($where)
                                                           ->like('company_name')
                                                           ->where('create_at','<= time',$create_at_last)
                                                           ->where('create_at','> time',$create_at_first)
                                                           ->page();                                
            }

    }
    /**
     * 添加会员
     * @auth true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function add()
    {
	    $this->error('无权限操作');
		$data=Db::name('CompanyUser')->where('nickname')->find();
		if(!$data){
		    $dbconf = $this->getconfig('vister_db');
		  $res2= Db::connect($dbconf)->table('view_commodity_orders');
		  //var_dump($res);
		  if($this->request->param('commodityId')){
		  $name= trim($this->request->param('name'));
		  $commodityId=$this->request->param('commodityId');
		  $payTime=$this->request->param('payTime');
		  $expritime=$this->request->param('expritime');
		  $data=[
		      //'name'=> $name,
		      'commodityId'=>$commodityId,
		      'payTime'=>$payTime,
		      'expritime'=>$expritime
		      ];
		      $data_name=['name'=>$name];
		      //var_dump($data);
		  
		    $res = Db::connect($dbconf)->table($this->table)->insert($data);
		    $res1= Db::connect($dbconf)->table($this->user)->insert($data_name);
		    $this->success('添加名单成功','');
		  }
			$this->_form($res2, 'form');
		
		}
		else{
				$this->error('名字已存在！');
		}
       
    }


    /**
     * 修改会员
     * @auth true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function edit()
    {
        $this->title = '修改会员信息';
        $dbconf = $this->getconfig('vister_db');
        $member_type = $this->request->param('member_type')?:NULL;
        $this->assign('member_type',$member_type);
         	
        if($this->request->isPost()){

            $id=$this->request->param('id');
		    $name= trim($this->request->param('name'));
		    $commodityId=$this->request->param('commodity_type');
		    $payTime=$this->request->param('payTime');
		    $expritime=$this->request->param('expritime');

            
            $member_info = Db::connect($dbconf)->table('view_user_store_member')->where('id = '.$id)->find();

            $commodity_info = Db::connect($dbconf)->table('commodity')->where('id = '.$commodityId)->find();
            /**
             * 插入订单数据
              **/
            //目前月为单位
            $commodity_type = 'M';
            if($member_type =='1'){
                $order_data = [
                  'userid' =>$member_info['uid'],
                  'openid' => $member_info['openid'],
                  'commodityId' => $commodity_info['id'],
                  'tradeNo' => makeOrdersn('HL'.$commodity_type),
                  // 'transaction_id' =>
                  'payTime' => time(),
                  'payType' => 3,
                  'status' => 2,
                  'amount' => 1,
                  'price' =>  $commodity_info['money'],
                  'expritime' => $expritime,
                  'createtime' => time(),
                  'remark' => '管理员设置订单'
                ];
                $res = Db::connect($dbconf)->table('commodity_orders')->insert($order_data);
            }

            //判断是否更换套餐---更新积分
            //
            //waiting code......
            //
            /**
             * 更新会员表信息
             **/
		    $member_data=[
		        //'name'=> $name,
		        'commodityid' => $commodity_info['id'],
		        'vip_date' => $expritime,
		        'create_at' => $payTime
		    ];
            $where=['id'=>$id];
            $res = Db::connect($dbconf)->table('store_member')->where($where)->data($member_data)->update();

            //废弃
            //$res = Db::table('store_member')->where($where)->setInc('frequency', $commodity_info['frequency']);

		    $this->success('修改名单成功','');
		  }
        $commodity_list = Db::connect($dbconf)->table('commodity')->select();
        $this->assign('commodity_list',$commodity_list);

        if($this->request->param('tmember_type')=='2'){
            $this->assign('member_type',2);
            $this->_form(Db::connect($dbconf)->table('view_company_store_member'), 'form');
        }else{
            $this->assign('member_type',1);
            $this->_form(Db::connect($dbconf)->table('view_user_store_member'), 'form');
        }
        
        // $name = trim($this->request->param('name')); 
        // $commodityId = trim($this->request->param('commodityId')); 
        // var_dump($name);
    }

    /**
     * 权限表单数据处理
     * @param array $data 表单数据
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function _form_filter(&$data)
    {
        if ($this->request->isGet()) {
            $where = ['status' => '1', 'is_deleted' => '0'];
            $this->auths = Db::name('company_user_auth')->where($where)->order('sort desc,id desc')->select();
            array_unshift($this->auths, ['id' => '0', 'title' => '所有权限', 'path' => '/']);
            $data['svn_authorize'] = isset($data['svn_authorize']) ? explode(',', $data['svn_authorize']) : [];
        } else {
            if (isset($data['svn_authorize']) && is_array($data['svn_authorize'])) {
                $data['svn_authorize'] = join(',', $data['svn_authorize']);
            } else {
                $data['svn_authorize'] = '';
            }
            // $macs = [];
            // foreach (explode(PHP_EOL, preg_replace("/\s+/", PHP_EOL, trim($data['mobile_macs']))) as $mac) {
            //     if (DataService::applyMacValue($mac)) $macs[] = $mac;
            // }
            // $data['mobile_macs'] = join(PHP_EOL, array_unique($macs));
        }
        
    }

    /**
     * 更改会员状态
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function state()
    {
        $dbconf = $this->getconfig('vister_db');
        if($this->request->isPost()){
            $status = $this->request->param('status');
            switch ($status) {
                case 1:
                    # 启用 code...
                    break;
                case 2:
                    # 冻结 code...
                    break;
                default:
                    # code...
                    break;
            }
        }
        $this->_save(Db::connect($dbconf)->table('store_member'), ['status' => $this->request->param('status')],'','id = '.$this->request->param('id'));
    }

    /**
     * 删除会员
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function remove()
    {
        $dbconf = $this->getconfig('vister_db');
        // $this->_delete($this->table);
		if($this->request->isPost()){      
		$id=trim($this->request->param('id'));
		// dump($id);
		$data=Db::connect($dbconf)->table('store_member')->where("id in ($id)")->data(['deletetime'=>time()])->update();
		if($data){
			$this->success('会员删除成功');
		}
		}
    }

}
